package nil.ed.lazy.io.utils;

import nil.ed.lazy.io.utils.output.NullOutputStream;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;

/**
 * @author lidelin
 * @since 1.0
 */
public class FileUtils {

    public static Checksum checkCRC32(String fp) throws IOException {
        return checkCRC32(new File(fp));
    }

    public static Checksum checkCRC32(File f) throws IOException{
        if (f.isDirectory()) {
            throw  new IOException("Cannot cal checksum for dir");
        }
        return checkCRC32(new BufferedInputStream(new FileInputStream(f)));
    }

    public static Checksum checkCRC32(InputStream in) throws IOException {
        Checksum checksum = new CRC32();
        try (InputStream checkIn = in = new CheckedInputStream(in, checksum)) {
            StreamUtils.copy(checkIn, new NullOutputStream());
        }
        return checksum;
    }

    public Checksum checkCRC32(byte[] bytes) throws IOException {
        return checkCRC32(new ByteArrayInputStream(bytes));
    }

}
